package org.lvxiao.example.redis;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Service;


@Service
public class RedisService {
	
	final static Logger log = LoggerFactory.getLogger(RedisService.class);
	
    @SuppressWarnings("rawtypes")
	@Autowired
    private RedisTemplate redisTemplate;
    
    @Autowired
    private RedisScriptService redisScriptService;
    
    /** 获取超时时间 */
    @SuppressWarnings("unchecked")
	public Long getExpireTime(String key){
    	return redisTemplate.getExpire(key);
    }

    /**
     * 设置超时时间
     * @param key
     * @param secExpireTime
     * @return
     */
    @SuppressWarnings("unchecked")
	public boolean setExpireTime(String key, long secExpireTime){
    	return redisTemplate.expire(key, secExpireTime, TimeUnit.SECONDS);
    }
    
    /**
     * 写入缓存
     * @param key
     * @param value
     * @return
     */
    @SuppressWarnings("unchecked")
	public boolean set(final String key, Object value) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            result = true;
        } catch (Exception e) {
        	log.error("set key value error", e);
        }
        return result;
    }
    
    /**   
     * 如果键已存在则返回false,不更新,防止覆盖。使用pipeline批处理方式(不关注返回值)   
     *  @return   
     */    
    @SuppressWarnings("unchecked")
	public boolean setNX(final String key, final Object value, final Long expireTime) {    
        boolean result = (boolean) redisTemplate.execute(new RedisCallback<Boolean>() {  
        	@Override
            public Boolean doInRedis(RedisConnection connection)    
                    throws DataAccessException { 
        		RedisSerializer valueSerializer = redisTemplate.getValueSerializer();
            	return connection.setNX(key.getBytes(), valueSerializer.serialize(value));
            }    
        });
        if (result && expireTime != null) {
        	redisTemplate.expire(key, expireTime, TimeUnit.SECONDS); //设置超时时间，释放内存
        }
        return result;
    }  
    
    /**
     * 写入缓存设置时效时间
     * @param key
     * @param value
     * @return
     */
    @SuppressWarnings("unchecked")
	public boolean set(final String key, Object value, Long expireTime) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
        	log.error("set key value expireTime error", e);
        }
        return result;
    }
    /**
     * 批量删除对应的value
     * @param keys
     */
    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }

    /**
     * 批量删除key
     * @param pattern
     */
    @SuppressWarnings("unchecked")
	public void removePattern(final String pattern) {
        Set<Serializable> keys = redisTemplate.keys(pattern);
        if (keys.size() > 0){
        	redisTemplate.delete(keys);
        }
    }
    /**
     * 删除对应的value
     * @param key
     */
    @SuppressWarnings("unchecked")
	public void remove(final String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
        }
    }
    /**
     * 判断缓存中是否有对应的value
     * @param key
     * @return
     */
    @SuppressWarnings("unchecked")
	public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }
    /**
     * 读取缓存
     * @param key
     * @return
     */
    @SuppressWarnings("unchecked")
	public Object get(final String key) {
        Object result = null;
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        result = operations.get(key);
        return result;
    }
    /**
     * 哈希 添加
     * @param key
     * @param hashKey
     * @param value
     */
    @SuppressWarnings("unchecked")
	public void hmSet(String key, Object hashKey, Object value){
        HashOperations<String, Object, Object>  hash = redisTemplate.opsForHash();
        hash.put(key,hashKey,value);
    }

    /**
     * 哈希 删除
     * @param key
     * @param hashKey
     * @param value
     */
    @SuppressWarnings("unchecked")
	public void hmRemove(String key, Object... hashKey){
    	HashOperations<String, Object, Object>  hash = redisTemplate.opsForHash();
    	hash.delete(key, hashKey);
    }
    
    /**
     * 哈希获取数据
     * @param key
     * @param hashKey
     * @return
     */
    @SuppressWarnings("unchecked")
	public Object hmGet(String key, Object hashKey){
        HashOperations<String, Object, Object>  hash = redisTemplate.opsForHash();
        return hash.get(key,hashKey);
    }
    
    /**
     * 哈希获取数据
     * @param key
     * @param hashKey
     * @return
     */
    @SuppressWarnings("unchecked")
	public Map<Object, Object> hmGet(String key){
        HashOperations<String, Object, Object>  hash = redisTemplate.opsForHash();
        return hash.entries(key);
    }

    /**
     * 列表添加
     * @param k
     * @param v
     */
    @SuppressWarnings("unchecked")
	public void lPush(String k,Object v){
        ListOperations<String, Object> list = redisTemplate.opsForList();
        list.rightPush(k,v);
    }

    /**
     * 列表获取
     * @param k
     * @param l
     * @param l1
     * @return
     */
    @SuppressWarnings("unchecked")
	public List<Object> lRange(String k, long l, long l1){
        ListOperations<String, Object> list = redisTemplate.opsForList();
        return list.range(k,l,l1);
    }

    /**
     * 集合添加
     * @param key
     * @param value
     */
    @SuppressWarnings("unchecked")
	public void add(String key,Object value){
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        set.add(key,value);
    }

    @SuppressWarnings("unchecked")
	private SetOperations<String, Object> getSetOperations() {
    	return redisTemplate.opsForSet();
    }
    
    /**
     * 集合(Set): 添加
     * @param key
     * @param value
     * @return 成功添加数量
     */
	public long sAdd(String key, Object ...values) {
		SetOperations<String, Object> setOperations = getSetOperations();
		return setOperations.add(key, values);
    }
	
	/**
	 * 集合(Set): 判断值是否存在集合中
	 * @param key
	 * @param value
	 * @return
	 */
	public boolean sExist(String key, Object value) {
		SetOperations<String, Object> opsForSet = getSetOperations();
		return opsForSet.isMember(key, value);
	}
	
	/**
	 * 集合(Set): 获取集合中所有的元素
	 * @param key
	 * @return
	 */
	public Set<Object> sGetAllMembers(String key){
		SetOperations<String, Object> opsForSet = getSetOperations();
		return opsForSet.members(key);
	}
	
	/**
	 * 集合(Set): 删除集合中元素
	 * @param key
	 * @param values
	 * @return 成功删除的数量
	 */
	public long sRemove(String key, Object ...values) {
		SetOperations<String, Object> opsForSet = getSetOperations();
		return opsForSet.remove(key, values);
	}
    
    /**
     * 集合获取
     * @param key
     * @return
     */
    @SuppressWarnings("unchecked")
	public Set<Object> setMembers(String key){
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        return set.members(key);
    }

    /**
     * 有序集合添加
     * @param key
     * @param value
     * @param scoure
     */
    @SuppressWarnings("unchecked")
	public void zAdd(String key,Object value,double scoure){
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        zset.add(key,value,scoure);
    }

    /**
     * 有序集合获取
     * @param key
     * @param scoure
     * @param scoure1
     * @return
     */
    @SuppressWarnings("unchecked")
	public Set<Object> rangeByScore(String key,double scoure,double scoure1){
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        return zset.rangeByScore(key, scoure, scoure1);
    }
    
    /**
     * 获取自增
     */
    @SuppressWarnings("unchecked")
	public Long increment(){
    	return redisTemplate.opsForValue().increment("increment", 1);
    }
    
    /**
     * 获取自增
     * @param key 自增KEY
     * @return 
     */
    @SuppressWarnings("unchecked")
	public Long increment(String key){
    	return redisTemplate.opsForValue().increment(key, 1);
    }
    
    /**
     * 获取自增
     * @param key 自增KEY
     * @param expireTime 失效时间
     * @return
     */
    @SuppressWarnings({ "unchecked"})
	public Long increment(String key, Integer expireTime){
    	if (expireTime == null || key == null || key.length() == 0) {
    		throw new NullPointerException("失效时间和KEY不能为空");
    	}
    	Long increment = this.increment(key);
    	Boolean hasSuccess = redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
    	if (!hasSuccess) {
    		throw new RuntimeException("设置失效时间失败: " + key);
    	}
    	return increment;
    }
    
    /**
     * 增量加减指定整数, 当增量后值小于0时失败, 返回-1
     * @param key 增量KEY值
     * @param decrement 增量整数, 负数则为减
     * @return 自减成功返回自减后的值, 失败返回-1, 为NULL 返回-2
     */
    public Long incrementGreaterThanZero(String key, long increment) {
    	return null;//(Long)redisScriptService.execute("increment-if-then-zero", Arrays.asList(key, String.valueOf(increment)), null);
    }
}
